package com.example.demo.story.impl;

import com.example.demo.story.NetStoryServiceAbstract;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Objects;

/**
 * @Author TCJ
 * @create 2024/6/27
 */
public class WanBaImpl extends NetStoryServiceAbstract {
	@Override
	public String getBaseUrl() {
		return "https://m.wanbaxsw.com";
	}

	@Override
	public String getReadUrl() {
		return getBaseUrl() + "/184896/";
	}

	@Override
	public void analysisChapter() {
		getRead(getReadUrl());
		Document html = super.getHtml(getReadUrl());
		Element pagelist = html.body().getElementsByClass("pagelist").get(0);
		Elements a = pagelist.getElementsByTag("a");
		a.forEach(item -> {
			if ("下一页".equals(item.text())){
				getRead(getBaseUrl() + item.attr("href"));
			}
		});

	}

	private void getRead(String readUrl) {
		Document html = super.getHtml(readUrl);
		Element select = html.body().getElementsByClass("read").get(0);
		Elements option = select.getElementsByTag("a");
		for (Element element : option) {
			super.dto.getChapter().put(element.text(), getBaseUrl() + element.attr("href"));
		}

	}

	@Override
	public String getContent(String url) {
		StringBuilder sb = new StringBuilder();
		nextContent(url, sb);
		return sb.toString();
	}

	private void nextContent(String url, StringBuilder sb) {
		Document html = super.getHtml(url);
		if (html == null){
			System.err.println("html为空" + html);
			getContent(url);
		}
		if (html.body() == null){
			System.err.println("body为空" + html);
			getHtml(url);
		}
		sb.append(Objects.requireNonNull(html.body().getElementsByClass("content")).text());

	}
}
